package com.budwk.app.fetchdata.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.budwk.app.base.utils.CoordinateUtils;
import com.budwk.app.base.utils.VideoCaptureUtils;
import com.budwk.app.fetchdata.models.HttpClientUtil;
import com.budwk.app.miniapp.utils.NutzIocUtils;
import com.budwk.app.oss.models.SysOss;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.wxprogram.models.Wx_area;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import com.budwk.app.fetchdata.models.FetchData_emergency;
import com.budwk.app.fetchdata.services.FetchdataEmergencyService;
import com.tencentcloudapi.iotvideo.v20191126.models.DeviceModelData;
import jodd.io.FileUtil;
import okio.Utf8;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.poi.ss.formula.functions.Offset;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.entity.Record;
import org.nutz.dao.entity.annotation.Id;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;
import org.nutz.lang.Strings;
import com.budwk.starter.common.openapi.annotation.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Array;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@IocBean
@At("/platform/fetchdata/spider/emergency/information")
@ApiDefinition(tag = "应急信息数据表")
@Slf4j
public class FetchdataEmergencyController {
    @Inject
    Dao dao;
    @Inject
    private FetchdataEmergencyService wxSpiderEmergencyInformationService;

    @Inject
    private SysUserService sysUserService;
    @Inject
    private SysOssService sysOssService;
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询应急信息数据表")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "addtime", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = FetchData_emergency.class
    )
    @ApiResponses(
            implementation = FetchData_emergency.class
    )
    //@SaCheckPermission("fetchdata.spider.emergency.information")
    public Result<?> list(@Param("..") FetchData_emergency bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) throws ParseException {
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        }

        if (bean.getInformationtitle() != null && Strings.isNotBlank(bean.getInformationtitle().toString())) {
            cnd.and("informationtitle", "like", "%" + bean.getInformationtitle() + "%");
        }

        if (bean.getInformationcontent() != null && Strings.isNotBlank(bean.getInformationcontent().toString())) {
            cnd.and("informationcontent", "like", "%" + bean.getInformationcontent() + "%");
        }

        if (bean.getProvince() != null && Strings.isNotBlank(bean.getProvince().toString())) {
            cnd.and("province", "like", "%" + bean.getProvince() + "%");
        }

        if (bean.getCity() != null && Strings.isNotBlank(bean.getCity().toString())) {
            cnd.and("city", "like", "%" + bean.getCity() + "%");
        }

        if (bean.getDistrict() != null && Strings.isNotBlank(bean.getDistrict().toString())) {
            cnd.and("district", "like", "%" + bean.getDistrict() + "%");
        }

        if (bean.getStreet() != null && Strings.isNotBlank(bean.getStreet().toString())) {
            cnd.and("street", "like", "%" + bean.getStreet() + "%");
        }

        if (bean.getInformationchannels() != null && Strings.isNotBlank(bean.getInformationchannels().toString())) {
            cnd.and("informationchannels", "like", "%" + bean.getInformationchannels() + "%");
        }

        if (bean.getReleasetime() != null && Strings.isNotBlank(bean.getReleasetime().toString())) {
            Instant instant = bean.getReleasetime().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("releasetime", "between", new Object[]{startdateStr, enddateStr});
        }

        if (bean.getAddtime() != null && Strings.isNotBlank(bean.getAddtime().toString())) {
            cnd.and("addtime", "like", "%" + bean.getAddtime().substring(0, 10) + "%");
        }

        if (bean.getAddperson() != null && Strings.isNotBlank(bean.getAddperson().toString())) {
            cnd.and("addperson", "like", "%" + bean.getAddperson() + "%");
        }

        if (bean.getCreatedate() != null && Strings.isNotBlank(bean.getCreatedate().toString())) {
            cnd.and("createdate", "like", "%" + bean.getCreatedate() + "%");
        }

        if (bean.getInformationmedia() != null && Strings.isNotBlank(bean.getInformationmedia().toString())) {
            cnd.and("informationmedia", "like", "%" + bean.getInformationmedia() + "%");
        }

        if (bean.getAddphone() != null && Strings.isNotBlank(bean.getAddphone().toString())) {
            cnd.and("addphone", "like", "%" + bean.getAddphone() + "%");
        }

        if (bean.getLatitude() != null && Strings.isNotBlank(bean.getLatitude().toString())) {
            cnd.and("latitude", "like", "%" + bean.getLatitude() + "%");
        }

        if (bean.getLongitude() != null && Strings.isNotBlank(bean.getLongitude().toString())) {
            cnd.and("longitude", "like", "%" + bean.getLongitude() + "%");
        }

        if (bean.getPicurl() != null && Strings.isNotBlank(bean.getPicurl().toString())) {
            cnd.and("picurl", "like", "%" + bean.getPicurl() + "%");
        }
        if (bean.getDisaster_type() != null && Strings.isNotBlank(bean.getDisaster_type().toString())) {
            cnd.and("disaster_type", "like", "%" + bean.getDisaster_type() + "%");
        }
        if (bean.getDisaster_address() != null && Strings.isNotBlank(bean.getDisaster_address().toString())) {
            cnd.and("disaster_address", "like", "%" + bean.getDisaster_address() + "%");
        }
        if (bean.getDisaster_class() != null && Strings.isNotBlank(bean.getDisaster_class().toString())) {
            cnd.and("disaster_class", "like", "%" + bean.getDisaster_class() + "%");
        }

        if (bean.getVideo_url() != null && Strings.isNotBlank(bean.getVideo_url().toString())) {
            cnd.and("video_url", "like", "%" + bean.getVideo_url() + "%");
        }
        if (bean.getDisaster_status() != null && Strings.isNotBlank(bean.getDisaster_status().toString())) {
            cnd.and("disaster_status", "like", "%" + bean.getDisaster_status() + "%");
        }

        if (bean.getIsshow() != null && Strings.isNotBlank(bean.getIsshow())) {
            if (bean.getIsshow().equals("0")) {
                cnd.and("isshow", "=", bean.getIsshow());
            }
            if (bean.getIsshow().equals("1")){
                cnd.and("isshow", "=", bean.getIsshow());
            }
            if (bean.getIsshow().equals("2")){
                cnd.and("isshow", "=", bean.getIsshow());
            }
            if (bean.getIsshow().equals("3")){
                cnd.and("isshow", "=", bean.getIsshow());
            }
            if (bean.getIsshow().equals("4")){
                cnd.and("isshow", "=", bean.getIsshow());
            }
            /*else {
                SqlExpressionGroup exps = new SqlExpressionGroup();
                exps = Cnd.exps("isshow", "=", "1").or("isshow", "=", "2").or("isshow", "=", "3");
                cnd.and(exps);

            }*/

        }

        cnd.and("informationmedia", "not like", "%东方祥云%");


        return Result.data(wxSpiderEmergencyInformationService.listPage(pageNo, pageSize, cnd));
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "新增应急信息数据表")
    @ApiFormParams(
            implementation = FetchData_emergency.class
    )
    @ApiResponses
    @SLog(tag = "新增应急信息数据表", value = "${args[0].id}")
    //@SaCheckPermission("fetchdata.spider.emergency.information.create")
    public Result<?> createData(@Param("..") FetchData_emergency wxSpiderEmergencyInformation, HttpServletRequest req) throws IOException {

        String address = wxSpiderEmergencyInformation.getProvince() + "，" + wxSpiderEmergencyInformation.getCity() + "，" + wxSpiderEmergencyInformation.getDistrict() + "，" + wxSpiderEmergencyInformation.getStreet();

        //Map map =CoordinateUtils.gtelatlng(address);
        List<Wx_area> fetch = dao.query(Wx_area.class, Cnd.where("whole_name", "=", address));

        String res = address;
        String b = "，";
        int count = (res.length() - res.replace(b, "").length()) / b.length();if (count != 0) {
            for (int i = count; i > 0; i--) {
                if (fetch.size() == 0 || fetch == null) {
                    address = address.substring(0, address.indexOf("，"/*,address.indexOf("，")+i*/));

                    if (address.charAt(address.length() - 1) == '，') {
                        address = address.substring(0, address.length() - 1);
                    }


                    fetch = dao.query(Wx_area.class, Cnd.where("whole_name", "=", address));


                }
                if (fetch.size() != 0) {
                    wxSpiderEmergencyInformation.setLongitude(fetch.get(0).getLon());
                    wxSpiderEmergencyInformation.setLatitude(fetch.get(0).getLat());
                } else {
                    wxSpiderEmergencyInformation.setLongitude("");
                    wxSpiderEmergencyInformation.setLatitude("");
                }
            }
        }


        //wxSpiderEmergencyInformation.setCreatedBy(SecurityUtil.getUserId());
        if (!wxSpiderEmergencyInformation.getVideo_url().toString().equals("")) {
            //if (videoUrl!=null){

            System.out.println("video===========" + wxSpiderEmergencyInformation.getVideo_url());
            String vUrl = wxSpiderEmergencyInformation.getVideo_url().toString();
            // 1.下载网络文件
            String[] videourls = wxSpiderEmergencyInformation.getVideo_url().toString().split(",");
            String saveFile = "";

            String uploadresult = "";
            JSONObject jsonObject = null;
            JSONObject dataObject = null;
            String videourlresult = "";
            String videourlresults = "";
            for (String videourl : videourls) {

                //==================================
                        /*InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
                        byte[] buffer = new byte[initialStream.available()];
                        initialStream.read(buffer);

                        File targetFile = new File("src/main/resources/targetFile.tmp");
                        OutputStream outStream = new FileOutputStream(targetFile);
                        outStream.write(buffer);*/

                //==================================
                System.out.println("videoUrl========" + videourl);
                int byteRead;

                //3.写入文件
                Date date = new Date();
                long timeStamp = date.getTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = simpleDateFormat.format(date);
                UUID.randomUUID().toString();
                saveFile = "D:\\CESHI\\VIDEO\\" + timeStamp + "_" + UUID.randomUUID().toString();

                //downVideo(videourl,saveFile);



                       /* File huawei =new File(saveFile);
                        FileInputStream inputStream = new FileInputStream(huawei);*/
                //MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);

                String requestUrl= NutzIocUtils.getPropertiesProxy().get("app.upload");
                //JSONObject requestUrlParam = new JSONObject();
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put("file", FileUtil.file(vUrl));
                //paramMap.put("grant_type", "authorization_code");


                        /*uploadresult = HttpUtil.post(requestUrl,paramMap);
                        jsonObject = JSONObject.parseObject(uploadresult);
                        dataObject = JSONObject.parseObject(jsonObject.get("data").toString());*/

                videourlresult = videourl.toString() + ",";
                videourlresults = videourlresults + videourlresult + ",";
                //richText=richText.toString().replace("replaceUrl",dataObject.get("url").toString());

            }
            wxSpiderEmergencyInformation.setVideo_url(videourlresults);

        } else {
            wxSpiderEmergencyInformation.setVideo_url("");
        }


        if (wxSpiderEmergencyInformation.getInformationcontent() != null || !wxSpiderEmergencyInformation.getInformationcontent().toString().isEmpty()) {
            //if (richText!=null||!richText.toString().isEmpty()) {
            String richText = wxSpiderEmergencyInformation.getInformationcontent();
            String richTextStr = richText.toString();
            String regex = "src=\"(.*?)\"";
            List<String> list = new ArrayList<>();

            Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
            Matcher ma = pa.matcher(richTextStr);
            while (ma.find()) {
                String src = ma.group();
                String regex1 = "(http(.*?)(.jpg|.png|jpg|gif))|(https(.*?)(.jpg|.png|jpg|gif))";
                Pattern pa1 = Pattern.compile(regex1, Pattern.DOTALL);
                Matcher ma1 = pa1.matcher(src);
                while (ma1.find()) {
                    list.add(ma1.group());
                }
            }
            for (String str : list) {
                log.info("解析后图片:" + str);
            }

            String imgStr = "";
            String imgUrl = "";
            if (!new File("D:\\CESHI\\IMG").exists()) {
                Path path = Paths.get("D:\\CESHI\\IMG");
                Path pathCreate = Files.createDirectory(path);
                imgUrl = pathCreate.toString();
            } else {
                imgUrl = "D:\\CESHI\\IMG";
            }
            String uploadresult = "";
            JSONObject jsonObject = null;
            JSONObject dataObject = null;
            String imgurlresult = "";
            String imgurlresults = "";
            File file;
            BufferedInputStream str = null;
            FileOutputStream out = null;
            for (String strURL : list) {
                if (!strURL.contains("dfsj-standard.obs")) {

                    System.out.println("strURL=============" + strURL);
                    strURL = strURL.replaceAll("(?is)<(.*?)>", "").replaceAll("\\s*|\t|\r|\n", "").replaceAll("&nbsp|&lt|&gt|&amp|&quot|&apos|&times|&divide", "");

                    String imageName = imgUrl + "\\" + strURL.substring(strURL.lastIndexOf("/") + 1, strURL.length());

                    file = new File(imageName);

                    /*file = new File(imageName);
                    InputStream inputStream = getInputStream();
                    byte[] data = new byte[1024];
                    int len = 0;
                    FileOutputStream fileOutputStream = null;
                    try {
                        fileOutputStream = new FileOutputStream(file);
                        while ((len = inputStream.read(data)) != -1) {
                            fileOutputStream.write(data, 0, len);

                        }
*/

                    try {
                        URL url = new URL(strURL);

                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();


                        //设置超时间为3秒
                        conn.setConnectTimeout(5000);
                        conn.setReadTimeout(5000);
                        conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36");

                        conn.connect();
                        //输出流

                        str = new BufferedInputStream(conn.getInputStream());


                        //控制流的大小为1k
                        byte[] bs = new byte[1024];

                        //读取到的长度
                        int len = 0;
                        //是否需要创建文件夹
                        file = new File(imageName);
                        //实例输出一个对象
                        out = new FileOutputStream(file);
                        //循环判断，如果读取的个数b为空了，则is.read()方法返回-1，具体请参考InputStream的read();
                        while ((len = str.read(bs)) != -1) {
                            //将对象写入到对应的文件中
                            out.write(bs, 0, len);
                        }
                        //刷新流
                        out.flush();


                        //关闭流
                       /* out.close();
                        str.close();*/
                        File huawei = new File(imageName);
                        FileInputStream inputStream = new FileInputStream(huawei);
                        //MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
                        String requestUrl= NutzIocUtils.getPropertiesProxy().get("app.upload");
                        //JSONObject requestUrlParam = new JSONObject();
                        HashMap<String, Object> paramMap = new HashMap<>();
                        paramMap.put("file", FileUtil.file(imageName));
                        //paramMap.put("grant_type", "authorization_code");


                        uploadresult = HttpUtil.post(requestUrl, paramMap);
                        if (!uploadresult.equals("")) {
                            richText = richText.toString().replace(strURL, "replaceUrl");
                        } else {
                            richText = richText.toString();
                        }
                        jsonObject = JSONObject.parseObject(uploadresult);
                        dataObject = JSONObject.parseObject(jsonObject.get("data").toString());


                        imgurlresult = dataObject.get("url").toString();
                        SysOss uploadOSS =sysOssService.upload(FileUtil.file(imageName));
                        uploadresult = uploadOSS.getUrl();
                        imgurlresults = imgurlresults + imgurlresult + ",";
                        richText = richText.toString().replace("replaceUrl", dataObject.get("url").toString());

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {

                        if (str != null) {
                            try {
                                str.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        if (out != null) {
                            try {
                                out.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                    }

                } else {
                    imgurlresults = imgurlresults + strURL + ",";
                    richText = richText.toString();
                }

            }
            //wxSpiderEmergencyInformation.setPicurl(imgurlresults);
            wxSpiderEmergencyInformation.setInformationcontent(richText.toString());

            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(date);
            wxSpiderEmergencyInformation.setAddtime(time);

        }

        wxSpiderEmergencyInformationService.insert(wxSpiderEmergencyInformation);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "新增应急信息数据表")
    @ApiFormParams(
            implementation = FetchData_emergency.class
    )
    @ApiResponses
    @SLog(tag = "新增应急信息数据表", value = "${args[0].id}")
    @SaCheckPermission("fetchdata.spider.emergency.information.create")
    public Result<?> create(@Param("..") FetchData_emergency wxSpiderEmergencyInformation, HttpServletRequest req) throws IOException {

        String address = wxSpiderEmergencyInformation.getProvince() + "，" + wxSpiderEmergencyInformation.getCity() + "，" + wxSpiderEmergencyInformation.getDistrict() + "，" + wxSpiderEmergencyInformation.getStreet();

        //Map map =CoordinateUtils.gtelatlng(address);
        List<Wx_area> fetch = dao.query(Wx_area.class, Cnd.where("whole_name", "=", address));

        String res = address;
        String b = "，";
        int count = (res.length() - res.replace(b, "").length()) / b.length();
        if (count != 0) {
            for (int i = count; i > 0; i--) {
                if (fetch.size() == 0 || fetch == null) {
                    address = address.substring(0, address.indexOf("，"/*,address.indexOf("，")+i*/));

                    if (address.charAt(address.length() - 1) == '，') {
                        address = address.substring(0, address.length() - 1);
                    }


                    fetch = dao.query(Wx_area.class, Cnd.where("whole_name", "=", address));


                }
                if (fetch.size() != 0) {
                    wxSpiderEmergencyInformation.setLongitude(fetch.get(0).getLon());
                    wxSpiderEmergencyInformation.setLatitude(fetch.get(0).getLat());
                } else {
                    wxSpiderEmergencyInformation.setLongitude("");
                    wxSpiderEmergencyInformation.setLatitude("");
                }
            }
        }


        wxSpiderEmergencyInformation.setCreatedBy(SecurityUtil.getUserId());
        if (!wxSpiderEmergencyInformation.getVideo_url().toString().equals("")) {
            //if (videoUrl!=null){

            System.out.println("video===========" + wxSpiderEmergencyInformation.getVideo_url());
            String vUrl = wxSpiderEmergencyInformation.getVideo_url().toString();
            // 1.下载网络文件
            String[] videourls = wxSpiderEmergencyInformation.getVideo_url().toString().split(",");
            String saveFile = "";

            String uploadresult = "";
            JSONObject jsonObject = null;
            JSONObject dataObject = null;
            String videourlresult = "";
            String videourlresults = "";
            for (String videourl : videourls) {

                //==================================
                        /*InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
                        byte[] buffer = new byte[initialStream.available()];
                        initialStream.read(buffer);

                        File targetFile = new File("src/main/resources/targetFile.tmp");
                        OutputStream outStream = new FileOutputStream(targetFile);
                        outStream.write(buffer);*/

                //==================================
                System.out.println("videoUrl========" + videourl);
                int byteRead;

                //3.写入文件
                Date date = new Date();
                long timeStamp = date.getTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = simpleDateFormat.format(date);
                UUID.randomUUID().toString();
                saveFile = "D:\\CESHI\\VIDEO\\" + timeStamp + "_" + UUID.randomUUID().toString();

                //downVideo(videourl,saveFile);



                       /* File huawei =new File(saveFile);
                        FileInputStream inputStream = new FileInputStream(huawei);*/
                //MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
                String requestUrl= NutzIocUtils.getPropertiesProxy().get("app.upload");
                //JSONObject requestUrlParam = new JSONObject();
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put("file", FileUtil.file(vUrl));
                //paramMap.put("grant_type", "authorization_code");


                        /*uploadresult = HttpUtil.post(requestUrl,paramMap);
                        jsonObject = JSONObject.parseObject(uploadresult);
                        dataObject = JSONObject.parseObject(jsonObject.get("data").toString());*/

                videourlresult = videourl.toString() + ",";
                videourlresults = videourlresults + videourlresult + ",";
                //richText=richText.toString().replace("replaceUrl",dataObject.get("url").toString());

            }
            wxSpiderEmergencyInformation.setVideo_url(videourlresults);

        } else {
            wxSpiderEmergencyInformation.setVideo_url("");
        }


        if (wxSpiderEmergencyInformation.getInformationcontent() != null || !wxSpiderEmergencyInformation.getInformationcontent().toString().isEmpty()) {
            //if (richText!=null||!richText.toString().isEmpty()) {
            String richText = wxSpiderEmergencyInformation.getInformationcontent();
            String richTextStr = richText.toString();
            String regex = "src=\"(.*?)\"";
            List<String> list = new ArrayList<>();

            Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
            Matcher ma = pa.matcher(richTextStr);
            while (ma.find()) {
                String src = ma.group();
                String regex1 = "(http(.*?)(.jpg|.png|jpg|gif))|(https(.*?)(.jpg|.png|jpg|gif))";
                Pattern pa1 = Pattern.compile(regex1, Pattern.DOTALL);
                Matcher ma1 = pa1.matcher(src);
                while (ma1.find()) {
                    list.add(ma1.group());
                }
            }
            for (String str : list) {
                log.info("解析后图片:" + str);
            }

            String imgStr = "";
            String imgUrl = "";
            if (!new File("D:\\CESHI\\IMG").exists()) {
                Path path = Paths.get("D:\\CESHI\\IMG");
                Path pathCreate = Files.createDirectory(path);
                imgUrl = pathCreate.toString();
            } else {
                imgUrl = "D:\\CESHI\\IMG";
            }
            String uploadresult = "";
            JSONObject jsonObject = null;
            JSONObject dataObject = null;
            String imgurlresult = "";
            String imgurlresults = "";
            File file;
            BufferedInputStream str = null;
            FileOutputStream out = null;
            for (String strURL : list) {
                if (!strURL.contains("dfsj-standard.obs")) {

                    System.out.println("strURL=============" + strURL);
                    strURL = strURL.replaceAll("(?is)<(.*?)>", "").replaceAll("\\s*|\t|\r|\n", "").replaceAll("&nbsp|&lt|&gt|&amp|&quot|&apos|&times|&divide", "");

                    String imageName = imgUrl + "\\" + strURL.substring(strURL.lastIndexOf("/") + 1, strURL.length());

                    file = new File(imageName);

                    /*file = new File(imageName);
                    InputStream inputStream = getInputStream();
                    byte[] data = new byte[1024];
                    int len = 0;
                    FileOutputStream fileOutputStream = null;
                    try {
                        fileOutputStream = new FileOutputStream(file);
                        while ((len = inputStream.read(data)) != -1) {
                            fileOutputStream.write(data, 0, len);

                        }
*/

                    try {
                        URL url = new URL(strURL);

                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();


                        //设置超时间为3秒
                        conn.setConnectTimeout(5000);
                        conn.setReadTimeout(5000);
                        conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36");

                        conn.connect();
                        //输出流

                        str = new BufferedInputStream(conn.getInputStream());


                        //控制流的大小为1k
                        byte[] bs = new byte[1024];

                        //读取到的长度
                        int len = 0;
                        //是否需要创建文件夹
                        file = new File(imageName);
                        //实例输出一个对象
                        out = new FileOutputStream(file);
                        //循环判断，如果读取的个数b为空了，则is.read()方法返回-1，具体请参考InputStream的read();
                        while ((len = str.read(bs)) != -1) {
                            //将对象写入到对应的文件中
                            out.write(bs, 0, len);
                        }
                        //刷新流
                        out.flush();


                        //关闭流
                       /* out.close();
                        str.close();*/
                        File huawei = new File(imageName);
                        FileInputStream inputStream = new FileInputStream(huawei);
                        //MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);


                        String requestUrl= NutzIocUtils.getPropertiesProxy().get("app.upload");
                        //JSONObject requestUrlParam = new JSONObject();
                        HashMap<String, Object> paramMap = new HashMap<>();
                        paramMap.put("file", FileUtil.file(imageName));
                        //paramMap.put("grant_type", "authorization_code");


                        uploadresult = HttpUtil.post(requestUrl, paramMap);
                        if (!uploadresult.equals("")) {
                            richText = richText.toString().replace(strURL, "replaceUrl");
                        } else {
                            richText = richText.toString();
                        }
                        jsonObject = JSONObject.parseObject(uploadresult);
                        dataObject = JSONObject.parseObject(jsonObject.get("data").toString());

                        imgurlresult = dataObject.get("url").toString();
                        imgurlresults = imgurlresults + imgurlresult + ",";
                        richText = richText.toString().replace("replaceUrl", dataObject.get("url").toString());

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {

                        if (str != null) {
                            try {
                                str.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        if (out != null) {
                            try {
                                out.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                    }

                } else {
                    imgurlresults = imgurlresults + strURL + ",";
                    richText = richText.toString();
                }

            }
            wxSpiderEmergencyInformation.setPicurl(imgurlresults);
            wxSpiderEmergencyInformation.setInformationcontent(richText.toString());
        }

        wxSpiderEmergencyInformationService.insert(wxSpiderEmergencyInformation);
        return Result.success();
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改应急信息数据表")
    @ApiFormParams(
            implementation = FetchData_emergency.class
    )
    @ApiResponses
    @SLog(tag = "修改应急信息数据表", value = "${args[0].id}")
    @SaCheckPermission("fetchdata.spider.emergency.information.update")
    public Result<?> update(@Param("..") FetchData_emergency wxSpiderEmergencyInformation, HttpServletRequest req) throws IOException {

        wxSpiderEmergencyInformation.setUpdatedBy(SecurityUtil.getUserId());
        if (!wxSpiderEmergencyInformation.getVideo_url().toString().equals("")) {
            //if (videoUrl!=null){

            System.out.println("video===========" + wxSpiderEmergencyInformation.getVideo_url());
            String vUrl = wxSpiderEmergencyInformation.getVideo_url().toString();
            // 1.下载网络文件
            String[] videourls = wxSpiderEmergencyInformation.getVideo_url().toString().split(",");
            String saveFile = "";

            String uploadresult = "";
            JSONObject jsonObject = null;
            JSONObject dataObject = null;
            String videourlresult = "";
            String videourlresults = "";
            for (String videourl : videourls) {

                //==================================
                        /*InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
                        byte[] buffer = new byte[initialStream.available()];
                        initialStream.read(buffer);

                        File targetFile = new File("src/main/resources/targetFile.tmp");
                        OutputStream outStream = new FileOutputStream(targetFile);
                        outStream.write(buffer);*/

                //==================================
                System.out.println("videoUrl========" + videourl);
                int byteRead;

                //3.写入文件
                Date date = new Date();
                long timeStamp = date.getTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = simpleDateFormat.format(date);
                UUID.randomUUID().toString();
                saveFile = "D:\\CESHI\\VIDEO\\" + timeStamp + "_" + UUID.randomUUID().toString();

                //downVideo(videourl,saveFile);



                       /* File huawei =new File(saveFile);
                        FileInputStream inputStream = new FileInputStream(huawei);*/
                //MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);

                String requestUrl= NutzIocUtils.getPropertiesProxy().get("app.upload");
                //JSONObject requestUrlParam = new JSONObject();
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put("file", FileUtil.file(vUrl));
                //paramMap.put("grant_type", "authorization_code");


                        /*uploadresult = HttpUtil.post(requestUrl,paramMap);
                        jsonObject = JSONObject.parseObject(uploadresult);
                        dataObject = JSONObject.parseObject(jsonObject.get("data").toString());*/

                videourlresult = videourl.toString() + ",";
                videourlresults = videourlresults + videourlresult + ",";
                //richText=richText.toString().replace("replaceUrl",dataObject.get("url").toString());

            }
            wxSpiderEmergencyInformation.setVideo_url(videourlresults);

        } else {
            wxSpiderEmergencyInformation.setVideo_url("");
        }


        if (wxSpiderEmergencyInformation.getInformationcontent() != null || !wxSpiderEmergencyInformation.getInformationcontent().toString().isEmpty()) {
            //if (richText!=null||!richText.toString().isEmpty()) {
            String richText = wxSpiderEmergencyInformation.getInformationcontent();
            String richTextStr = richText.toString();
            String regex = "src=\"(.*?)\"";
            List<String> list = new ArrayList<>();

            Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
            Matcher ma = pa.matcher(richTextStr);
            while (ma.find()) {
                String src = ma.group();
                String regex1 = "(http(.*?)(.jpg|.png|jpg|gif))|(https(.*?)(.jpg|.png|jpg|gif))";
                Pattern pa1 = Pattern.compile(regex1, Pattern.DOTALL);
                Matcher ma1 = pa1.matcher(src);
                while (ma1.find()) {
                    list.add(ma1.group());
                }
            }
            for (String str : list) {
                log.info("解析后图片:" + str);
            }

            String imgStr = "";
            String imgUrl = "";
            if (!new File("D:\\CESHI\\IMG").exists()) {
                Path path = Paths.get("D:\\CESHI\\IMG");
                Path pathCreate = Files.createDirectory(path);
                imgUrl = pathCreate.toString();
            } else {
                imgUrl = "D:\\CESHI\\IMG";
            }
            String uploadresult = "";
            JSONObject jsonObject = null;
            JSONObject dataObject = null;
            String imgurlresult = "";
            String imgurlresults = "";
            File file;
            BufferedInputStream str = null;
            FileOutputStream out = null;
            for (String strURL : list) {
                if (!strURL.contains("dfsj-standard.obs")) {
                    System.out.println("strURL=============" + strURL);
                    strURL = strURL.replaceAll("(?is)<(.*?)>", "").replaceAll("\\s*|\t|\r|\n", "").replaceAll("&nbsp|&lt|&gt|&amp|&quot|&apos|&times|&divide", "");

                    String imageName = imgUrl + "\\" + strURL.substring(strURL.lastIndexOf("/") + 1, strURL.length());

                    file = new File(imageName);

                    /*file = new File(imageName);
                    InputStream inputStream = getInputStream();
                    byte[] data = new byte[1024];
                    int len = 0;
                    FileOutputStream fileOutputStream = null;
                    try {
                        fileOutputStream = new FileOutputStream(file);
                        while ((len = inputStream.read(data)) != -1) {
                            fileOutputStream.write(data, 0, len);

                        }
*/

                    try {
                        URL url = new URL(strURL);

                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();


                        //设置超时间为3秒
                        conn.setConnectTimeout(3 * 1000);
                        //防止屏蔽程序抓取而返回403错误
                        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  //                 conn.connect();
                        conn.connect();
                        //输出流

                        str = new BufferedInputStream(conn.getInputStream());


                        //控制流的大小为1k
                        byte[] bs = new byte[1024];

                        //读取到的长度
                        int len = 0;
                        //是否需要创建文件夹
                        file = new File(imageName);
                        //实例输出一个对象
                        out = new FileOutputStream(file);
                        //循环判断，如果读取的个数b为空了，则is.read()方法返回-1，具体请参考InputStream的read();
                        while ((len = str.read(bs)) != -1) {
                            //将对象写入到对应的文件中
                            out.write(bs, 0, len);
                        }
                        //刷新流
                        out.flush();


                        //关闭流
                       /* out.close();
                        str.close();*/
                        File huawei = new File(imageName);
                        FileInputStream inputStream = new FileInputStream(huawei);
                        //MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
                        String requestUrl= NutzIocUtils.getPropertiesProxy().get("app.upload");
                        //JSONObject requestUrlParam = new JSONObject();
                        HashMap<String, Object> paramMap = new HashMap<>();
                        paramMap.put("file", FileUtil.file(imageName));
                        //paramMap.put("grant_type", "authorization_code");


                        uploadresult = HttpUtil.post(requestUrl, paramMap);
                        if (!uploadresult.equals("")) {
                            richText = richText.toString().replace(strURL, "replaceUrl");
                        } else {
                            richText = richText.toString();
                        }
                        jsonObject = JSONObject.parseObject(uploadresult);
                        dataObject = JSONObject.parseObject(jsonObject.get("data").toString());

                        imgurlresult = dataObject.get("url").toString();
                        imgurlresults = imgurlresults + imgurlresult + ",";
                        richText = richText.toString().replace("replaceUrl", dataObject.get("url").toString());

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {

                        if (str != null) {
                            try {
                                str.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        if (out != null) {
                            try {
                                out.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                    }

                } else {
                    imgurlresults = imgurlresults + strURL + ",";
                    richText = richText.toString();
                }

            }

            // wzy 2023-6-27
            if (StringUtils.isNotBlank(imgurlresults)) wxSpiderEmergencyInformation.setPicurl(imgurlresults);
            wxSpiderEmergencyInformation.setInformationcontent(richText.toString());
        }
        wxSpiderEmergencyInformationService.updateIgnoreNull(wxSpiderEmergencyInformation);
        return Result.success();
    }

    @At("/get")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取应急信息数据表")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SaCheckPermission("fetchdata.spider.emergency.information")
    public Result<?> getData(@Param("id") String id, HttpServletRequest req) {
        FetchData_emergency wxSpiderEmergencyInformation = wxSpiderEmergencyInformationService.fetch(id);
        if (wxSpiderEmergencyInformation == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        return Result.data(wxSpiderEmergencyInformation);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除应急信息数据表")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "删除应急信息数据表", value = "${args[0]}")
    @SaCheckPermission("fetchdata.spider.emergency.information.delete")
    public Result<?> delete(@Param("id") String id, HttpServletRequest req) {
        FetchData_emergency wxSpiderEmergencyInformation = wxSpiderEmergencyInformationService.fetch(id);
        if (wxSpiderEmergencyInformation == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        wxSpiderEmergencyInformationService.delete(id);
        req.setAttribute("_slog_msg", wxSpiderEmergencyInformation.getId());
        return Result.success();
    }


    @At("/addData")
    @Ok("json")
    @POST
    @ApiOperation(name = "文本框新增数据")
    @ApiFormParams()
    @SLog(tag = "文本框新增数据", value = "${args[0]}")
    @SaCheckPermission("fetchdata.spider.emergency.information.addData")
    public Result<?> addData(@Param("disasterType") Object disasterType,
                             @Param("fixedFormat") Object fixedFormat,
                             @Param("richText") Object richText,
                             @Param("disasterStatus") Object disasterStatus,
                             @Param("video_url") Object videoUrl,
                             @Param("addperson") Object addperson,
                             @Param("addphone") Object addphone,
                             @Param("isshow") Object isshow) throws Exception {


        FetchData_emergency fetchData_emergency = new FetchData_emergency();
        fetchData_emergency.setIsshow(isshow.toString());
        fetchData_emergency.setAddphone(addphone.toString());
        fetchData_emergency.setAddperson(addperson.toString());
        //fixedFormat=fixedFormat.toString().replace("：",",");

        if (disasterType != null || !disasterType.toString().isEmpty()) {
            if (fixedFormat != null || !fixedFormat.toString().isEmpty()) {
                fetchData_emergency.setDisaster_type(disasterType.toString());
                fetchData_emergency.setDisaster_status(disasterStatus.toString());
                String result = "";
                if (fixedFormat.toString().substring(0, 3).contains("内容：")) {
                    result = getStringBetweenTwoChars(fixedFormat.toString(), "内容：", "链接：").replaceAll("：", ":");
                    if (result.length() < 15) {
                        result = result;
                    } else {
                        result = result.substring(0, 15);
                    }


                    fixedFormat = "标题：" + result + "\n" + "摘要：" + "这是一个摘要" + (fixedFormat.toString().replace("\n", "").replace("内容：" + getStringBetweenTwoChars(fixedFormat.toString(), "内容：", "链接："), "")).replace("链接：", "\n链接：").replace("时间：", "\n时间：")
                            .replace("来源：", "\n来源：").replace("作者：", "\n作者：").replace("属性：", "\n属性：").replace("涉及关键词：", "\n涉及关键词：").replace("转发数：", "\n转发数：").replace("评论数：", "\n评论数：").replace("精准地域：", "\n精准地域：")
                            .replace("信息等级：", "\n信息等级：").replace("舆情类型：", "\n舆情类型：");


                }
                String[] fixedFormats = fixedFormat.toString().split("\n");
                fetchData_emergency.setDisaster_address(fixedFormats[10].replace("精准地域：", ""));
                fetchData_emergency.setInformationtitle(fixedFormats[0].substring(3));
                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                fetchData_emergency.setReleasetime(ft.parse(fixedFormats[3].substring(3) + ":00"));
                fetchData_emergency.setInformationmedia(fixedFormats[4].substring(3));
                fetchData_emergency.setInformationchannels(fixedFormats[5].substring(3));
                fetchData_emergency.setAddtime(ft.format(new Date()));


                if (videoUrl != null) {

                    // VideoCaptureUtils.fetchFrameToFile(videoUrl.toString(),"D:\\CESHI\\IMG",1);


                    System.out.println("video===========" + videoUrl);
                    String vUrl = videoUrl.toString();
                    // 1.下载网络文件
                    String[] videourls = videoUrl.toString().split(",");
                    String saveFile = "";

                    String uploadresult = "";
                    JSONObject jsonObject = null;
                    JSONObject dataObject = null;
                    String videourlresult = "";
                    String videourlresults = "";
                    for (String videourl : videourls) {


                        System.out.println("videoUrl========" + videourl);
                        int byteRead;

                        //3.写入文件
                        Date date = new Date();
                        long timeStamp = date.getTime();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String time = simpleDateFormat.format(date);
                        UUID.randomUUID().toString();
                        saveFile = "D:\\CESHI\\VIDEO\\" + timeStamp + "_" + UUID.randomUUID().toString();

                        String requestUrl= NutzIocUtils.getPropertiesProxy().get("app.upload");
                        //JSONObject requestUrlParam = new JSONObject();
                        HashMap<String, Object> paramMap = new HashMap<>();
                        paramMap.put("file", FileUtil.file(vUrl));
                        //paramMap.put("grant_type", "authorization_code");


                        /*uploadresult = HttpUtil.post(requestUrl,paramMap);
                        jsonObject = JSONObject.parseObject(uploadresult);
                        dataObject = JSONObject.parseObject(jsonObject.get("data").toString());*/

                        videourlresult = videourl.toString() + ",";
                        videourlresults = videourlresults + videourlresult + ",";
                        //richText=richText.toString().replace("replaceUrl",dataObject.get("url").toString());

                    }
                    fetchData_emergency.setVideo_url(videourlresults);

                } else {
                    fetchData_emergency.setVideo_url("");
                }
                fetchData_emergency.setAddperson(addperson.toString());
                String[] addresss = fixedFormats[10].substring(5).split(",");
                List<String> provinces = new ArrayList();
                List<String> city = new ArrayList();
                List<String> district = new ArrayList();
                List<String> street = new ArrayList();
                for (String address : addresss) {
                    if (address.contains("省") || address.contains("特别行政区") || address.contains("自治区") || address.contains("北京市") || address.contains("天津市") || address.contains("上海市") || address.contains("重庆市")) {
                        provinces.add(address);
                    }
                    if (address.contains("市")/*||address.contains("北京市")||address.contains("天津市")||address.contains("上海市")||address.contains("重庆市")*/) {
                        city.add(address);
                    }
                    if ((address.contains("区") || address.contains("县")) && !address.contains("特别行政区") && !address.contains("自治区")) {
                        district.add(address);
                    }
                    if (address.contains("乡") || address.contains("镇") || address.contains("街道")) {
                        street.add(address);
                    }
                    if (address.contains("海外") || address.contains("其他") || address.contains("其它")) {
                        provinces.add(address);
                        break;
                    }
                }
                String address = "";
                if (provinces.size() != 0) {
                    address = address + provinces.get(0) + "，";
                }
                if (city.size() != 0) {
                    address = address + city.get(0) + "，";
                }
                if (district.size() != 0) {
                    address = address + district.get(0) + "，";
                }
                if (street.size() != 0) {
                    address = address + street.get(0);
                }


                if (address.charAt(address.length() - 1) == '，') {
                    address = address.substring(0, address.length() - 1);
                }
                List<Wx_area> fetch = dao.query(Wx_area.class, Cnd.where("whole_name", "=", address));


                String res = address;
                String b = "，";
                int count = (res.length() - res.replace(b, "").length()) / b.length();
                if (count != 0) {
                    for (int i = count; i > 0; i--) {
                        if (fetch.size() == 0 || fetch == null) {
                            address = address.substring(0, address.indexOf("，"/*,address.indexOf("，")+i*/));

                            if (address.charAt(address.length() - 1) == '，') {
                                address = address.substring(0, address.length() - 1);
                            }


                            fetch = dao.query(Wx_area.class, Cnd.where("whole_name", "=", address));


                        }

                        if (provinces.size() != 0) {
                            fetchData_emergency.setProvince(provinces.get(0));
                        } else {
                            fetchData_emergency.setProvince("");
                        }
                        if (city.size() != 0) {
                            fetchData_emergency.setCity(city.get(0));
                        } else {
                            fetchData_emergency.setCity("");
                        }
                        if (district.size() != 0) {
                            fetchData_emergency.setDistrict(district.get(0));
                        } else {
                            fetchData_emergency.setDistrict("");
                        }
                        if (street.size() != 0) {
                            fetchData_emergency.setStreet(street.get(0));
                        } else {
                            fetchData_emergency.setStreet("");
                        }
                        if (fetch.size() != 0) {
                            fetchData_emergency.setLongitude(fetch.get(0).getLon());
                            fetchData_emergency.setLatitude(fetch.get(0).getLat());
                        } else {
                            fetchData_emergency.setLongitude("");
                            fetchData_emergency.setLatitude("");
                        }
                    }

                } else {
                    fetchData_emergency.setProvince(provinces.get(0));

                }
            }


            if (!richText.toString().equals("") || !richText.toString().isEmpty()) {
                String richTextStr = richText.toString();
                String regex = "src=\"(.*?)\"";
                List<String> list = new ArrayList<>();

                Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
                Matcher ma = pa.matcher(richTextStr);
                while (ma.find()) {
                    String src = ma.group();
                    String regex1 = "(http(.*?)(.jpg|.png|jpg|gif))|(https(.*?)(.jpg|.png|jpg|gif))";
                    Pattern pa1 = Pattern.compile(regex1, Pattern.DOTALL);
                    Matcher ma1 = pa1.matcher(src);
                    while (ma1.find()) {
                        list.add(ma1.group());
                    }
                }
                for (String str : list) {
                    log.info("解析后图片:" + str);
                }

                String imgStr = "";
                String imgUrl = "";
                if (!new File("D:\\CESHI\\IMG").exists()) {
                    Path path = Paths.get("D:\\CESHI\\IMG");
                    Path pathCreate = Files.createDirectory(path);
                    imgUrl = pathCreate.toString();
                } else {
                    imgUrl = "D:\\CESHI\\IMG";
                }
                String uploadresult = "";
                JSONObject jsonObject = null;
                JSONObject dataObject = null;
                String imgurlresult = "";
                String imgurlresults = "";
                File file;
                BufferedInputStream str = null;
                FileOutputStream out = null;
                for (String strURL : list) {
                    if (!strURL.contains("dfsj-standard.obs")) {

                        System.out.println("strURL=============" + strURL);
                        strURL = strURL.replaceAll("(?is)<(.*?)>", "").replaceAll("\\s*|\t|\r|\n", "")/*.replaceAll("&nbsp|&lt|&gt|&amp|&quot|&apos|&times|&divide","")*/;
                        String imageName = "";
                        // String imageName = imgUrl + "\\" + strURL.substring(strURL.lastIndexOf("/") + 1, strURL.length());
                        if (strURL.contains("jpg") || strURL.contains("jpeg") || strURL.contains("JPG") || strURL.contains("JPEG")) {
                            imageName = imgUrl + "\\" + UUID.randomUUID() + ".jpg";
                        }
                        if (strURL.contains("png") || strURL.contains("PNG")) {
                            imageName = imgUrl + "\\" + UUID.randomUUID() + ".png";
                        }
                        if (strURL.contains("gif") || strURL.contains("GIF")) {
                            imageName = imgUrl + "\\" + UUID.randomUUID() + ".gif";
                        }
                        file = new File(imageName);

                        try {
                            URL url = new URL(strURL);

                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();


                            //设置超时间为3秒
                            conn.setConnectTimeout(50000);
                            conn.setReadTimeout(50000);
                            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                            //conn.addRequestProperty("cookie","www3.wipo.int");
                            conn.connect();
                            //输出流

                            str = new BufferedInputStream(conn.getInputStream());


                            //控制流的大小为1k
                            byte[] bs = new byte[1024];

                            //读取到的长度
                            int len = 0;
                            //是否需要创建文件夹
                            file = new File(imageName);
                            //实例输出一个对象
                            out = new FileOutputStream(file);
                            //循环判断，如果读取的个数b为空了，则is.read()方法返回-1，具体请参考InputStream的read();
                            while ((len = str.read(bs)) != -1) {
                                //将对象写入到对应的文件中
                                out.write(bs, 0, len);
                            }
                            //刷新流
                            out.flush();


                            //关闭流
                       /* out.close();
                        str.close();*/
                            File huawei = new File(imageName);
                            FileInputStream inputStream = new FileInputStream(huawei);
                            //MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
                            String requestUrl= NutzIocUtils.getPropertiesProxy().get("app.upload");
                            //JSONObject requestUrlParam = new JSONObject();
                            HashMap<String, Object> paramMap = new HashMap<>();
                            paramMap.put("file", FileUtil.file(imageName));
                            //paramMap.put("grant_type", "authorization_code");


                            uploadresult = HttpUtil.post(requestUrl, paramMap);

                            if (!uploadresult.equals("")) {
                                richText = richText.toString().replace(strURL, "replaceUrl");
                            } else {
                                richText = richText.toString();
                            }
                            jsonObject = JSONObject.parseObject(uploadresult);
                            dataObject = JSONObject.parseObject(jsonObject.get("data").toString());

                            imgurlresult = dataObject.get("url").toString();
                            imgurlresults = imgurlresults + imgurlresult + ",";
                            richText = richText.toString().replace("replaceUrl", dataObject.get("url").toString());

                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } finally {

                            if (str != null) {
                                try {
                                    str.close();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                            if (out != null) {
                                try {
                                    out.close();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }

                        }

                    } else {
                        imgurlresults = imgurlresults + strURL + ",";
                        richText = richText.toString();
                    }
                }
                fetchData_emergency.setPicurl(imgurlresults);
                fetchData_emergency.setInformationcontent(richText.toString());
            } else {
                if (fixedFormat.toString().contains("摘要：")) {
                    richText = "<p>" + fixedFormat.toString().substring(fixedFormat.toString().indexOf("摘要："), fixedFormat.toString().indexOf("链接：")).replace("摘要：", "").replace("链接：", "") + "</p>";
                    fetchData_emergency.setInformationcontent(richText.toString());
                } else {
                    fetchData_emergency.setInformationcontent("");
                }


            }

        }
        wxSpiderEmergencyInformationService.insert(fetchData_emergency);
        return Result.success();
    }

    @At("/getCount")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取信息总条数")
    @ApiFormParams()
    @SLog(tag = "获取信息总条数", value = "${args[0]}")
    public Result getCount() {
        Sys_user sys_user = sysUserService.fetch(SecurityUtil.getUserId());

        Cnd cndqixiang = Cnd.NEW();
        cndqixiang.and("informationmedia", "like", "%国家预警信息发布中心%");
        cndqixiang.or("informationmedia", "like", "%贵州省气象局%");
        cndqixiang.and("province", "!=", "国外");
        cndqixiang.and("province", "!=", "");
        //if (sys_user.get)

        int qixiang = wxSpiderEmergencyInformationService.count(cndqixiang);

        Cnd cnddizhen = Cnd.NEW();
        cnddizhen.and("informationmedia", "like", "%中国地震台网%");
        cnddizhen.and("province", "!=", "国外");
        cnddizhen.and("province", "!=", "");
        int dizhen = wxSpiderEmergencyInformationService.count(cnddizhen);

        Cnd cndgzszrzyt = Cnd.NEW();
        cndgzszrzyt.and("informationmedia", "like", "%贵州省自然资源厅%");
        cndgzszrzyt.and("province", "!=", "国外");
        cndgzszrzyt.and("province", "!=", "");
        int gzszrzyt = wxSpiderEmergencyInformationService.count(cndgzszrzyt);

        Cnd cndgzsnynct = Cnd.NEW();
        cndgzsnynct.and("informationmedia", "like", "%贵州省农业农村厅%");
        cndgzsnynct.and("province", "!=", "国外");
        cndgzsnynct.and("province", "!=", "");
        //cndgzsnynct.having(cndgzsnynct.wrap("count(province)>0"));
        int gzsnynct = wxSpiderEmergencyInformationService.count(cndgzsnynct);

        Cnd cndgzsjtyst = Cnd.NEW();
        cndgzsjtyst.and("informationmedia", "like", "%贵州省交通运输厅%");
        cndgzsjtyst.and("province", "!=", "国外");
        cndgzsjtyst.and("province", "!=", "");
        int gzsjtyst = wxSpiderEmergencyInformationService.count(cndgzsjtyst);

        Cnd cndgzsslt = Cnd.NEW();
        cndgzsslt.and("informationmedia", "like", "%贵州省水利厅%");
        cndgzsslt.and("province", "!=", "国外");
        cndgzsslt.and("province", "!=", "");
        int gzsslt = wxSpiderEmergencyInformationService.count(cndgzsslt);

        Cnd cndshi = Cnd.NEW();
        cndshi.and("informationchannels", "like", "%市%");
        int shi = wxSpiderEmergencyInformationService.count(cndshi);

        Cnd cndxian = Cnd.NEW();
        cndxian.and("informationchannels", "like", "%县%");
        int xian = wxSpiderEmergencyInformationService.count(cndxian);

        Map map = new HashMap();
        map.put("qixiang", qixiang);//气象
        map.put("dizhen", dizhen);//地震
        map.put("dijishi", shi);//地级市
        map.put("xianji", xian);//县级
        map.put("gzszrzyt", gzszrzyt);//自然
        map.put("gzsnynct", gzsnynct);//农业农村
        map.put("gzsjtyst", gzsjtyst);//交通
        map.put("gzsslt", gzsslt);//水利


        Result result = Result.NEW();
        result.addData(map);

        return result;
    }

    @At("/getProvinceCount")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取省份信息条数")
    @ApiFormParams()
    @SLog(tag = "获取省份信息条数", value = "${args[0]}")
    public Result getProvinceCount(@Param("type") Object type, @Param("totalChineseProvinces") Object totalChineseProvinces) {
        Result result = Result.NEW();


        if (type.toString().equals("贵州省气象局")) {
            String str = JSONObject.toJSONString(totalChineseProvinces);
            List<JSONObject> models = JSONObject.parseArray(str, JSONObject.class);

            for (int j = 0; j < models.size(); j++) {
                Cnd cnd = Cnd.NEW();
                cnd.and("informationmedia", "like", "%" + type.toString() + "%");
                cnd.or("informationmedia", "like", "%" + "国家预警信息发布中心" + "%");
                cnd.and("province", "like", "%" + models.get(j).get("name") + "%");


                //SqlExpressionGroup e1 = Cnd.exps("province", "=", "''").or("province", "is", null);

                //cnd.and(e1);
                //cnd.having(Cnd.wrap("count(province)>0"));
                Integer province = wxSpiderEmergencyInformationService.count(cnd);

                models.get(j).put("count", province);

            }

            result.addData(models);


        } else {


            String str = JSONObject.toJSONString(totalChineseProvinces);
            List<JSONObject> models = JSONObject.parseArray(str, JSONObject.class);

            for (int j = 0; j < models.size(); j++) {
                Cnd cnd = Cnd.NEW();
                cnd.and("informationmedia", "like", "%" + type.toString() + "%");
                cnd.and("province", "like", "%" + models.get(j).get("name") + "%");
                //cnd.having(Cnd.wrap("count(province)>0"));
                Integer province = wxSpiderEmergencyInformationService.count(cnd);

                models.get(j).put("count", province);

            }
            result.addData(models);


        }


        return result;


    }

    @At("/getCountAll")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取省市区获取信息条数")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "name", description = "名字", example = "贵州"),
                    @ApiFormParam(name = "typeaddress", description = "省市区", example = "省"),
                    @ApiFormParam(name = "type", description = "类型", example = "贵州省农业农村厅")
            }
    )
    @SLog(tag = "获取省市区获取信息条数", value = "${args[0]}")
    public Result getCountAll(@Param("name") Object name, @Param("typeaddress") Object typeaddress, @Param("type") Object type) {

        Result result = Result.NEW();
        if (type.toString().equals("贵州省交通运输厅") || type.toString().equals("贵州省农业农村厅")) {
            String sqls = "SELECT * from wx_spider_emergency_information  where province like '%" + name + "%'  and informationmedia like '%" + type + "%' ";
            Sql sql = Sqls.create(sqls);

            List<JSONObject> list = new ArrayList<JSONObject>();
            sql.setCallback(new SqlCallback() {
                @Override
                public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                    while (rs.next()) {
                        JSONObject obj = new JSONObject();
                        obj.put("name", rs.getString("informationtitle"));
                        obj.put("informationcontent", rs.getString("informationcontent"));
                        //obj.put("informationcontent", rs.getString("informationcontent"));
                        obj.put("street", rs.getString("street"));
                        /*if (rs.getString("street")==null||rs.getString("street").isEmpty()||rs.getString("street").equals("")){
                            obj.put("address", rs.getString("province")+rs.getString("city")+rs.getString("district"));
                        }else {
                            obj.put("address", rs.getString("province")+rs.getString("city")+rs.getString("district")+rs.getString("street"));

                        }
*/
                        obj.put("address", rs.getString("province"));
                        obj.put("releasetime", rs.getString("releasetime"));
                        obj.put("informationmedia", rs.getString("informationmedia"));
                        obj.put("longitude", rs.getString("longitude"));
                        obj.put("latitude", rs.getString("latitude"));
                        obj.put("type", typeaddress.toString());
                        obj.put("notclass", "is");

                        list.add(obj);
                    }
                    return list;
                }
            });//实体回调，不构建实体类
            Entity<Record> entity = dao.getEntity(Record.class);//Record是Nutz自带的一个类，查一下就知道了
            sql.setEntity(entity);
            dao.execute(sql);
            List<Record> map = sql.getList(Record.class);
            result.addData(list);
            return result;


        }


        if (type.toString().equals("贵州省气象局")) {
            if (typeaddress.toString().contains("省")) {
                String sqls = " SELECT count(city),city,province from wx_spider_emergency_information where province like '%" + name + "%' and (informationmedia like '%" + type + "%' or informationmedia like '%国家预警信息发布中心%') GROUP BY city,province HAVING count(city)>0";
                Sql sql = Sqls.create(sqls);

                List<JSONObject> list = new ArrayList<JSONObject>();
                sql.setCallback(new SqlCallback() {
                    @Override
                    public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                        while (rs.next()) {
                            Map location = CoordinateUtils.getLatAndLngByAddrforTengxun(rs.getString("city"));
                            JSONObject obj = new JSONObject();
                            obj.put("count", rs.getString("count"));
                            obj.put("city", rs.getString("city"));
                            obj.put("type", typeaddress.toString());
                            obj.put("latitude", location.get("lat"));
                            obj.put("longitude", location.get("lng"));
                            obj.put("id", location.get("code"));
                            obj.put("notclass", "not");
                            list.add(obj);
                        }
                        return list;
                    }
                });//实体回调，不构建实体类
                Entity<Record> entity = dao.getEntity(Record.class);//Record是Nutz自带的一个类，查一下就知道了
                sql.setEntity(entity);
                dao.execute(sql);
                List<Record> map = sql.getList(Record.class);
                result.addData(list);
                return result;

            }
            if (typeaddress.toString().contains("市")) {
                String sqls = " SELECT count(district),district,city from wx_spider_emergency_information where city like '%" + name + "%' and (informationmedia like '%" + type + "%' or informationmedia like '%国家预警信息发布中心%')  GROUP BY district,city HAVING count(district)>0";
                Sql sql = Sqls.create(sqls);

                List<JSONObject> list = new ArrayList<JSONObject>();
                sql.setCallback(new SqlCallback() {
                    @Override
                    public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                        while (rs.next()) {
                            Map location = CoordinateUtils.getLatAndLngByAddrforTengxun(rs.getString("district"));
                            JSONObject obj = new JSONObject();
                            obj.put("count", rs.getString("count"));
                            obj.put("district", rs.getString("district"));
                            obj.put("city", rs.getString("city"));
                            obj.put("type", typeaddress.toString());
                            obj.put("latitude", location.get("lat"));
                            obj.put("longitude", location.get("lng"));
                            obj.put("id", location.get("code"));
                            obj.put("notclass", "not");

                            list.add(obj);
                        }
                        return list;
                    }
                });//实体回调，不构建实体类
                Entity<Record> entity = dao.getEntity(Record.class);//Record是Nutz自带的一个类，查一下就知道了
                sql.setEntity(entity);
                dao.execute(sql);
                List<Record> map = sql.getList(Record.class);
                result.addData(list);
                return result;
            }

            if (typeaddress.toString().contains("区") || typeaddress.toString().contains("县")) {
                String sqls = "SELECT * from wx_spider_emergency_information  where district like '%" + name + "%'  and (informationmedia like '%" + type + "%' or informationmedia like '%国家预警信息发布中心%')";
                Sql sql = Sqls.create(sqls);

                List<JSONObject> list = new ArrayList<JSONObject>();
                sql.setCallback(new SqlCallback() {
                    @Override
                    public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                        while (rs.next()) {
                            JSONObject obj = new JSONObject();
                            obj.put("name", rs.getString("informationtitle"));
                            obj.put("informationcontent", rs.getString("informationcontent"));
                            //obj.put("informationcontent", rs.getString("informationcontent"));
                            obj.put("street", rs.getString("street"));
                            if (rs.getString("street") == null || rs.getString("street").isEmpty() || rs.getString("street").equals("")) {
                                obj.put("address", rs.getString("province") + rs.getString("city") + rs.getString("district"));
                            } else {
                                obj.put("address", rs.getString("province") + rs.getString("city") + rs.getString("district") + rs.getString("street"));

                            }
                            obj.put("releasetime", rs.getString("releasetime"));
                            obj.put("informationmedia", rs.getString("informationmedia"));
                            obj.put("longitude", rs.getString("longitude"));
                            obj.put("latitude", rs.getString("latitude"));
                            obj.put("type", typeaddress.toString());
                            obj.put("notclass", "is");

                            list.add(obj);
                        }
                        return list;
                    }
                });//实体回调，不构建实体类
                Entity<Record> entity = dao.getEntity(Record.class);//Record是Nutz自带的一个类，查一下就知道了
                sql.setEntity(entity);
                dao.execute(sql);
                List<Record> map = sql.getList(Record.class);
                result.addData(list);
                return result;
            }


        } else {
            if (typeaddress.toString().contains("省")) {
                String sqls = " SELECT count(city),city,province from wx_spider_emergency_information where province like '%" + name + "%' and informationmedia like '%" + type + "%' GROUP BY city,province HAVING count(city)>0";
                Sql sql = Sqls.create(sqls);

                List<JSONObject> list = new ArrayList<JSONObject>();
                sql.setCallback(new SqlCallback() {
                    @Override
                    public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                        while (rs.next()) {
                            Map location = CoordinateUtils.getLatAndLngByAddrforTengxun(rs.getString("city"));
                            JSONObject obj = new JSONObject();
                            obj.put("count", rs.getString("count"));
                            obj.put("city", rs.getString("city"));
                            obj.put("type", typeaddress.toString());
                            obj.put("latitude", location.get("lat"));
                            obj.put("longitude", location.get("lng"));
                            obj.put("id", location.get("code"));
                            obj.put("notclass", "not");
                            list.add(obj);
                        }
                        return list;
                    }
                });//实体回调，不构建实体类
                Entity<Record> entity = dao.getEntity(Record.class);//Record是Nutz自带的一个类，查一下就知道了
                sql.setEntity(entity);
                dao.execute(sql);
                List<Record> map = sql.getList(Record.class);
                result.addData(list);
                return result;

            }
            if (typeaddress.toString().contains("市")) {
                String sqls = " SELECT count(district),district,city from wx_spider_emergency_information where city like '%" + name + "%' and informationmedia like '%" + type + "%'  GROUP BY district,city HAVING count(district)>0";
                Sql sql = Sqls.create(sqls);

                List<JSONObject> list = new ArrayList<JSONObject>();
                sql.setCallback(new SqlCallback() {
                    @Override
                    public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                        while (rs.next()) {
                            Map location = CoordinateUtils.getLatAndLngByAddrforTengxun(rs.getString("district"));
                            JSONObject obj = new JSONObject();
                            obj.put("count", rs.getString("count"));
                            obj.put("district", rs.getString("district"));
                            obj.put("city", rs.getString("city"));
                            obj.put("type", typeaddress.toString());
                            obj.put("latitude", location.get("lat"));
                            obj.put("longitude", location.get("lng"));
                            obj.put("id", location.get("code"));
                            obj.put("notclass", "not");
                            list.add(obj);
                        }
                        return list;
                    }
                });//实体回调，不构建实体类
                Entity<Record> entity = dao.getEntity(Record.class);//Record是Nutz自带的一个类，查一下就知道了
                sql.setEntity(entity);
                dao.execute(sql);
                List<Record> map = sql.getList(Record.class);
                result.addData(list);
                return result;
            }

            if (typeaddress.toString().contains("区") || typeaddress.toString().contains("县")) {
                String sqls = " SELECT * from wx_spider_emergency_information  where district like '%" + name + "%'  and informationmedia like '%" + type + "%'";
                Sql sql = Sqls.create(sqls);

                List<JSONObject> list = new ArrayList<JSONObject>();
                sql.setCallback(new SqlCallback() {
                    @Override
                    public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                        while (rs.next()) {
                            JSONObject obj = new JSONObject();
                            obj.put("name", rs.getString("informationtitle"));
                            obj.put("informationcontent", rs.getString("informationcontent"));
                            obj.put("informationcontent", rs.getString("informationcontent"));
                            obj.put("street", rs.getString("street"));
                            if (rs.getString("street") == null || rs.getString("street").isEmpty() || rs.getString("street").equals("")) {
                                obj.put("address", rs.getString("province") + rs.getString("city") + rs.getString("district"));
                            } else {
                                obj.put("address", rs.getString("province") + rs.getString("city") + rs.getString("district") + rs.getString("street"));

                            }
                            obj.put("releasetime", rs.getString("releasetime"));
                            obj.put("informationmedia", rs.getString("informationmedia"));
                            obj.put("longitude", rs.getString("longitude"));
                            obj.put("latitude", rs.getString("latitude"));

                            obj.put("type", typeaddress.toString());
                            obj.put("notclass", "is");
                            list.add(obj);
                        }
                        return list;
                    }
                });//实体回调，不构建实体类
                Entity<Record> entity = dao.getEntity(Record.class);//Record是Nutz自带的一个类，查一下就知道了
                sql.setEntity(entity);
                dao.execute(sql);
                List<Record> map = sql.getList(Record.class);
                result.addData(list);
                return result;
            }
        }

        return result;
    }


    @At("/getnotclass")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取未分类数据")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "name", description = "名字", example = "贵州"),
                    @ApiFormParam(name = "typeaddress", description = "省市区", example = "省"),
                    @ApiFormParam(name = "type", description = "类型", example = "贵州省农业农村厅")
            }
    )
    @SLog(tag = "获取未分类数据", value = "${args[0]}")
    public Result getnotclass(@Param("name") Object name, @Param("typeaddress") Object typeaddress, @Param("type") Object type) {
        Result result = Result.NEW();
        if (type.toString().equals("贵州省气象局")) {
            if (typeaddress.toString().contains("省")) {
                String sqls = "SELECT * from wx_spider_emergency_information  where province like '%" + name + "%'  and informationmedia like '%" + type + "%' and (city is NULL or city='')";
                Sql sql = Sqls.create(sqls);

                List<JSONObject> list = new ArrayList<JSONObject>();
                sql.setCallback(new SqlCallback() {
                    @Override
                    public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                        while (rs.next()) {
                            JSONObject obj = new JSONObject();
                            obj.put("name", rs.getString("informationtitle"));
                            obj.put("informationcontent", rs.getString("informationcontent"));
                            obj.put("informationcontent", rs.getString("informationcontent"));
                            obj.put("street", rs.getString("street"));
                            if (rs.getString("street") == null || rs.getString("street").isEmpty() || rs.getString("street").equals("")) {
                                obj.put("address", rs.getString("province") + rs.getString("city") + rs.getString("district"));
                            } else {
                                obj.put("address", rs.getString("province") + rs.getString("city") + rs.getString("district") + rs.getString("street"));

                            }
                            obj.put("releasetime", rs.getString("releasetime"));
                            obj.put("informationmedia", rs.getString("informationmedia"));
                            obj.put("longitude", rs.getString("longitude"));
                            obj.put("latitude", rs.getString("latitude"));

                            obj.put("type", typeaddress.toString());

                            list.add(obj);
                        }
                        return list;
                    }
                });//实体回调，不构建实体类
                Entity<Record> entity = dao.getEntity(Record.class);//Record是Nutz自带的一个类，查一下就知道了
                sql.setEntity(entity);
                dao.execute(sql);
                List<Record> map = sql.getList(Record.class);
                result.addData(list);
                return result;

            }
            if (typeaddress.toString().contains("市")) {
                String sqls = "SELECT * from wx_spider_emergency_information  where city like '%" + name + "%'  and informationmedia like '%" + type + "%' and (district is NULL or district='')";
                Sql sql = Sqls.create(sqls);

                List<JSONObject> list = new ArrayList<JSONObject>();
                sql.setCallback(new SqlCallback() {
                    @Override
                    public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                        while (rs.next()) {
                            JSONObject obj = new JSONObject();
                            obj.put("name", rs.getString("informationtitle"));
                            obj.put("informationcontent", rs.getString("informationcontent"));
                            obj.put("informationcontent", rs.getString("informationcontent"));
                            obj.put("street", rs.getString("street"));
                            if (rs.getString("street") == null || rs.getString("street").isEmpty() || rs.getString("street").equals("")) {
                                obj.put("address", rs.getString("province") + rs.getString("city") + rs.getString("district"));
                            } else {
                                obj.put("address", rs.getString("province") + rs.getString("city") + rs.getString("district") + rs.getString("street"));

                            }
                            obj.put("releasetime", rs.getString("releasetime"));
                            obj.put("informationmedia", rs.getString("informationmedia"));
                            obj.put("longitude", rs.getString("longitude"));
                            obj.put("latitude", rs.getString("latitude"));

                            obj.put("type", typeaddress.toString());

                            list.add(obj);
                        }
                        return list;
                    }
                });//实体回调，不构建实体类
                Entity<Record> entity = dao.getEntity(Record.class);//Record是Nutz自带的一个类，查一下就知道了
                sql.setEntity(entity);
                dao.execute(sql);
                List<Record> map = sql.getList(Record.class);
                result.addData(list);
                return result;

            }
            if (typeaddress.toString().contains("区") || typeaddress.toString().contains("县")) {
                String sqls = "SELECT * from wx_spider_emergency_information where district like '%" + name + "%'  and (informationmedia like '%" + type + "%' or informationmedia like '%国家预警信息发布中心%')";
                Sql sql = Sqls.create(sqls);

                List<JSONObject> list = new ArrayList<JSONObject>();
                sql.setCallback(new SqlCallback() {
                    @Override
                    public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                        while (rs.next()) {
                            JSONObject obj = new JSONObject();
                            obj.put("name", rs.getString("informationtitle"));
                            obj.put("informationcontent", rs.getString("informationcontent"));
                            obj.put("informationcontent", rs.getString("informationcontent"));
                            obj.put("street", rs.getString("street"));
                            if (rs.getString("street") == null || rs.getString("street").isEmpty() || rs.getString("street").equals("")) {
                                obj.put("address", rs.getString("province") + rs.getString("city") + rs.getString("district"));
                            } else {
                                obj.put("address", rs.getString("province") + rs.getString("city") + rs.getString("district") + rs.getString("street"));

                            }
                            obj.put("releasetime", rs.getString("releasetime"));
                            obj.put("informationmedia", rs.getString("informationmedia"));
                            obj.put("longitude", rs.getString("longitude"));
                            obj.put("latitude", rs.getString("latitude"));

                            obj.put("type", typeaddress.toString());

                            list.add(obj);
                        }
                        return list;
                    }
                });//实体回调，不构建实体类
                Entity<Record> entity = dao.getEntity(Record.class);//Record是Nutz自带的一个类，查一下就知道了
                sql.setEntity(entity);
                dao.execute(sql);
                List<Record> map = sql.getList(Record.class);
                result.addData(list);
                return result;

            }
        } else {


        }


        return result;
    }



   /* @At("/uploadVideo")
    @Ok("json")
    @POST
    @ApiOperation(name = "上传视频")
    @ApiFormParams()
    @SLog(tag = "上传视频", value = "${args[0]}")
    public String qiniuUpload(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        List<MultipartFile> files = params.getFiles("file");
        for (int i=0; i < files.size();i++) {
            String requestUrl = "http://140.210.211.155:10086/common/upload";
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("file", FileUtil.file(imageName));
            uploadresult = HttpUtil.post(requestUrl,paramMap);

            kodeUploadServiceImpl.uploadFiles(files.get(i));
            System.out.println("success:" + files.get(i));
        }
        return "complete";
    }*/



    /*@At("/uploadVideo")
    @Ok("json")
    @POST
    @ApiOperation(name = "上传视频")
    @ApiFormParams()
    @SLog(tag = "上传视频", value = "${args[0]}")
    public String uploadVideo(@Param("")String videoPath) throws FileNotFoundException {
        String uploadresult="";
        JSONObject jsonObject=null;
        JSONObject dataObject=null;
        String videourlresult="";
        String videourlresults="";

        File huawei =new File(videoPath);
        FileInputStream inputStream = new FileInputStream(huawei);
        //MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);

        String requestUrl = "http://140.210.211.155:10086/common/upload";
        //JSONObject requestUrlParam = new JSONObject();
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("file", FileUtil.file(videoPath));
        //paramMap.put("grant_type", "authorization_code");


        uploadresult = HttpUtil.post(requestUrl,paramMap);
        jsonObject = JSONObject.parseObject(uploadresult);
        dataObject = JSONObject.parseObject(jsonObject.get("data").toString());

        videourlresult=dataObject.get("url").toString()+",";
        videourlresults=videourlresults+videourlresult+",";
        //richText=richText.toString().replace("replaceUrl",dataObject.get("url").toString());

        fetchData_emergency.setVideo_url(videourlresult);



        return  "";
    }*/


    private InputStream getInputStream() {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;

        try {
            URL url = new URL("文件地址");
            httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置网络连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置应用程序要从网络连接读取数据
            httpURLConnection.setDoInput(true);

            httpURLConnection.setRequestMethod("GET");
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                // 从服务器返回一个输入流
                inputStream = httpURLConnection.getInputStream();

            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return inputStream;
    }

    public static String getStringBetweenTwoChars(String str, String startChar, String endChar) {
        String regex = startChar + "([^" + endChar + "]*)" + endChar;
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str.replace("：", ":"));
        if (matcher.find()) {
            return matcher.group(1);
        }
        return str.substring(3, 18);
    }

    /**
     * 下载视频
     *
     * @param videoUrl     视频网络地址
     * @param downloadPath 视频保存地址
     */
    public static boolean downVideo(String videoUrl, String downloadPath) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        RandomAccessFile randomAccessFile = null;
        boolean re;
        try {

            URL url = new URL(videoUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Range", "bytes=0-");
            connection.connect();
            if (connection.getResponseCode() / 100 != 2) {
                System.out.println("连接失败...");
                return false;
            }
            inputStream = connection.getInputStream();
            int downloaded = 0;
            int fileSize = connection.getContentLength();
            randomAccessFile = new RandomAccessFile(downloadPath, "rw");
            while (downloaded < fileSize) {
                byte[] buffer = null;
                if (fileSize - downloaded >= 1000000) {
                    buffer = new byte[1000000];
                } else {
                    buffer = new byte[fileSize - downloaded];
                }
                int read = -1;
                int currentDownload = 0;
                long startTime = System.currentTimeMillis();
                while (currentDownload < buffer.length) {
                    read = inputStream.read();
                    buffer[currentDownload++] = (byte) read;
                }
                long endTime = System.currentTimeMillis();
                double speed = 0.0;
                if (endTime - startTime > 0) {
                    speed = currentDownload / 1024.0 / ((double) (endTime - startTime) / 1000);
                }
                randomAccessFile.write(buffer);
                downloaded += currentDownload;
                randomAccessFile.seek(downloaded);
                System.out.printf(downloadPath + "下载了进度:%.2f%%,下载速度：%.1fkb/s(%.1fM/s)%n", downloaded * 1.0 / fileSize * 10000 / 100,
                        speed, speed / 1000);
            }
            re = true;
            return re;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            re = false;
            return re;
        } catch (IOException e) {
            e.printStackTrace();
            re = false;
            return re;
        } finally {
            try {
                connection.disconnect();
                inputStream.close();
                randomAccessFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[6024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }


    public static String delHtmlTags(String htmlStr) {
        //定义script的正则表达式，去除js可以防止注入
        String scriptRegex = "<script[^>]*?>[\\s\\S]*?<\\/script>";
        //定义style的正则表达式，去除style样式，防止css代码过多时只截取到css样式代码
        String styleRegex = "<style[^>]*?>[\\s\\S]*?<\\/style>";
        //定义HTML标签的正则表达式，去除标签，只提取文字内容
        String htmlRegex = "<[^>]+>";
        //定义空格,回车,换行符,制表符
        String spaceRegex = "\\s*|\t|\r|\n";

        // 过滤script标签
        htmlStr = htmlStr.replaceAll(scriptRegex, "");
        // 过滤style标签
        htmlStr = htmlStr.replaceAll(styleRegex, "");
        // 过滤html标签
        htmlStr = htmlStr.replaceAll(htmlRegex, "");
        // 过滤空格等
        htmlStr = htmlStr.replaceAll(spaceRegex, "");
        return htmlStr.trim(); // 返回文本字符串
    }

    public String remove(String s, String string, int i) {

        if (i == 1) {

            int j = s.indexOf(string);

            s = s.substring(0, j) + s.substring(j + 1);

            i--;

            return s;

        } else {

            int j = s.indexOf(string);

            i--;

            return s.substring(0, j + 1) + remove(s.substring(j + 1), string, i);

        }

    }


}
